package com.hh.erp.interceptor;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.hh.erp.util.DateTimeUtil;
import com.hh.erp.util.SqlUtil;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;


@Intercepts({
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
    @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)})
@Slf4j
public class MyBatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
    	long starttime = System.currentTimeMillis();
        Object returnValue = invocation.proceed();
        long time = System.currentTimeMillis() - starttime;

        if(invocation.getArgs()[0] != null && invocation.getArgs()[0] instanceof MappedStatement) {
            //这里打印SQL
            String sql = SqlUtil.getSql(invocation);
            StringBuilder str = new StringBuilder(150);
            str.append(DateTimeUtil.getDateTime());
            str.append(" default - ");
            str.append(sql);
            str.append(" (");
            str.append(time);
            str.append(" milliseconds)");
            System.out.println(str.toString());
        }
        return returnValue;
    }
}

